package com.situ.springboot.controller;

import com.situ.springboot.entity.User;
import com.situ.springboot.service.IUserService;
import com.situ.springboot.util.JSONResult;
import com.situ.springboot.util.LayUITableResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

// @RestController = @Controller + @ResponseBody
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/getUserListPage")
    public String getUserListPage() {
        return "user_list";
    }

    // /?page=1&limit=10
    @RequestMapping("/selectByPage")
    @ResponseBody
    public LayUITableResult selectByPage(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer limit) {
        System.out.println("UserController.selectByPage");
        LayUITableResult layUITableResult = userService.selectByPage(page, limit);
        return layUITableResult;
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public JSONResult deleteById(Integer id) {
        System.out.println("UserController.deleteById id: " + id);
        return userService.deleteById(id);
    }

    @RequestMapping("/deleteAll")
    @ResponseBody
    public JSONResult deleteById(Integer[] ids) {
        System.out.println("UserController.deleteAll ");
        return userService.deleteByAll(ids);
    }


    @RequestMapping("/getLoginPage")
    public String getLoginPage() {
        return "login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public JSONResult login(String name, String password, String code, HttpSession session) {
        System.out.println("UserController.login");
        String sessionCode = (String) session.getAttribute("sessionCode");
        if (!sessionCode.equals(code)) {
            // return new JSONResult(JSONResult.ERROR, "验证码错误");
            return JSONResult.error("验证码错误");
        }

        User user = userService.login(name, password);
        if (user == null) {
            return JSONResult.error("用户名或密码错误");
        } else {
            session.setAttribute("user", user);
            return JSONResult.ok("登录成功");
        }
    }
}
